<template>
  <el-upload
    class="avatar-uploader"
    list-type="picture-card"
    :show-file-list="showFileList"
    :multiple="multiple"
    :limit="limit"
    :action="actionUrl"
    :disabled="disabled"
    :on-success="handleSuccess"
    :on-change="handleChange"
    name="files"
    :on-remove="handleRemove"
    :on-preview="handlePictureCardPreview"
    :file-list="fileList"
    :before-upload="beforeAvatarUpload"
  >
    <!-- <template #tip>
      <div class="el-upload__tip">{{ tip }}</div>
    </template> -->
    <template #default>
      <el-icon>
        <Plus />
      </el-icon>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img
      w-full
      :src="dialogImageUrl"
      alt="Preview Image"
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRefs, emits, computed } from 'vue';
const emits = defineEmits(['success', 'remove', 'handleChange']);
const props = defineProps({
  actionUrl: {
    type: String,
    default: ''
  },
  showFileList: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  },

  fileList: {
    type: Array,
    default() {
      return [];
    }
  }
});
const dialogVisible = ref(false);
const dialogImageUrl = ref('');
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/jpg' || rawFile.type == 'image/png'|| rawFile.type == 'image/bmp')) {
    ElMessage.error('请上传jpeg、jpg、png、bmp格式文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传文件不能超过 5MB!')
    return false
  }
  return true
}
const handleChange = (uploadFile, uploadFiles) => {
  emits('handleChange', uploadFile.raw, uploadFiles);
};
const handleSuccess = (response, file, fileList) => {
  emits('success', response, file, fileList);
};

const handleRemove = (file, fileList) => {
  emits('remove', file, fileList);
};
</script>

<style scoped>
.avatar-uploader {
  height: 151px;
  overflow: hidden;
}
</style>
